//
//  Helper.swift
//  WBDemo
//
//  Created by Jin on 26/04/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import Foundation

//定义一个泛型函数
func encode<T>(of model:T,options:[CodingUserInfoKey:Any]!) throws where T:Codable {
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    
    if options != nil { encoder.userInfo = options }
    
    let data = try encoder.encode(model)
    JLog(message: String(data: data, encoding: .utf8))
    
}

func decode<T>(response:String ,of: T.Type) throws -> T where T:Codable {
    let data = response.data(using: .utf8)!
    let decoder = JSONDecoder()
    
    //处理异常
    do {
        let model = try decoder.decode(T.self, from: data)
        return model
    }catch(DecodingError.dataCorrupted(let context)){
        dump(context)
        exit(-1)
    }
    catch(DecodingError.keyNotFound(let path,let context)){
        dump(context)
        dump(path)
        exit(-1)
    }
    catch(DecodingError.typeMismatch(let type, let context)){
        dump(context)
        dump(type)
        exit(-1)
    }
    
}
